/* 登录路由
 * @Author: Leil 
 * @Date: 2018-08-19 00:36:38 
 * @Last Modified by: Leil
 * @Last Modified time: 2018-08-24 01:23:53
 */
const sha1 = require('sha1')
const express = require('express')
const router = express.Router()
const AdminModel = require('../models/admin')

router.use((req, res, next) => {
    if (req.session.user) {
        req.flash('error', '已登录')
        return res.redirect('/admin')
    }
    next()
})

router.get('/', (req, res) => {
    res.render('login')
})

// 登录表单提交
router.post('/', (req, res) => {
    const name = req.fields.name
    const password = req.fields.password
    try {
        checkAdminAndPwd(name, password)
    } catch (error) {
        // req.flash('error', error.message)
        // return res.redirect('back')
        return res.send({error: error.message})
    }

    AdminModel.getAdminByName(name)
    .then(user => {
        if (!user) {
            // req.flash('error', '用户名不存在')
            // return res.redirect('back')
            return res.send({error: '用户名不存在'})
        }
        if (sha1(password) !== user.password) {
            // req.flash('error', '用户名或密码错误')
            // return res.redirect('back')
            return res.send({error: '用户名或密码错误'})
        }
        // req.flash('success', '登录成功!')
        let data = {
            success: '登录成功',
            redirect: '/admin'
        }
        delete user.password
        // 将用户保存到请求头信息session中
        req.session.user = user  // 写入session
        return res.send(data)
    })
    .catch(e => {
        console.error(e)
    })
})

// 检测管理员用户名和密码
const checkAdminAndPwd = function (name, password) {
    if (!name.length) {
        throw new Error('请填写用户名!')
    }
    if (!password.length) {
        throw new Error('请填写密码!')
    }
}

module.exports = router